var app = getApp();
const storeAlone = "plugin.store-alone-temp.frontend.fightGroups.fight-groups.get-member-join-teams";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    language: '',
    info: {},
    active: 0,
    // more
    page: 1, // 分页数，当前页数
    isLoadMore: true, // 判断是否要加载更多的标志
    total_page: 0, // 总页数
    timer: null,
    type: 'group',
    // 拼团限制 start
    is_frequency: 0,
    member: [],
    frequency: 0,
    // 拼团限制 end
    yhShow: false,
    group_member_id: null,
    zhpObj: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.tag) {
      this.setData({
        active: Number(options.tag)
      });
    }
    if (options.types == 'zhpGroup') {
      this.getDataZhp(this.data.active);
      let obj = ['正在拼团', '拼团成功', '拼团失败'];
      wx.setNavigationBarTitle({
        title: '我的珍惠拼',
      });
      this.setData({
        type: options.types,
        zhpObj: obj
      });

    } else {
      this.getData(0);
    }
  },
  // 珍惠拼易货
  zhpYh(e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    this.data.group_member_id = id;
    let urlStr = app.getNetAddresss("plugin.zhp-group-lottery.frontend.goods.validate-barter");
    urlStr += "&group_member_id=" + id;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            barter_order_sn: res.data.barter_order_sn,
            barter_value: res.data.barter_value,
            barter_plugin_name: res.data.barter_plugin_name,
            yhShow: true
          });
        } else {
          wx.showToast({
            title: res.msg,
            duration: 1000,
            icon: 'none'
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  submityh(tag) {
    let that = this;
    let _url = tag == 1 ? 'plugin.zhp-group-lottery.frontend.goods.sendAction' : 'plugin.zhp-group-lottery.frontend.goods.barter-action';
    let urlStr = app.getNetAddresss(_url);
    urlStr += "&group_member_id=" + this.data.group_member_id;
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            yhShow: false
          });
          wx.showModal({
            title: '',
            content: res.msg,
            showCancel: true,
            success(res) {
              if (res.confirm) {
                that.getDataZhp(that.data.active);
              } else if (res.cancel) {
                console.log('用户点击取消');
              }
            }
          });
        } else {
          wx.showToast({
            title: res.msg,
            duration: 1000,
            icon: 'none'
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  cancelyh() {
    this.setData({
      yhShow: false
    });
  },
  zhpSendAction(e) {
    let id = e.currentTarget.dataset.id;
    this.data.group_member_id = id;
    wx.showModal({
      title: '',
      content: '订单选择发货',
      success: res => {
        if (res.confirm) {
          // console.log('用户点击确定')
          this.submityh(1);
        } else if (res.cancel) {
          // console.log('用户点击取消')
        }
      }
    });
  },
  // 易货end
  showPopover(e) {
    let index = e.currentTarget.dataset.index;
    let _isShow = this.data.info[index].showPopover;
    this.setData({
      ['info[' + index + '].showPopover']: !_isShow
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync('langIndex');
    this.setData({
      'language': language.en
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // 页面被被销毁的时候，清除定时器
    clearTimeout(this.data.timer);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getData(0);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isLoadMore) {
      this.getMoreData();
    } else {
      wx.showToast({
        title: '没有更多数据',
        icon: 'none'
      });
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  onChange(e) {
    this.setData({
      timeData: e.detail,
    });
  },
  // 时间戳差值
  getTimeDifference(Timestamp) {
    var now = Date.parse(new Date());
    let time = Timestamp < 1000000000000 ? Timestamp * 1000 : Timestamp;
    if (time - now > 0) {
      return time - now;
    } else if (time - now <= 0) {
      return 0;
    }
  },
  getDataZhp(ind) {
    let that = this;
    let urlStr = app.getNetAddresss('plugin.zhp-group-lottery.frontend.group-member.get-group-member-list');
    app._getNetWork({
      url: urlStr,
      data: {
        is_win: ind
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            total_page: res.data.last_page,
            isLoadMore: true,
            info: res.data.data,
            page: this.data.page,
          });
          for (let i = 0; i < that.data.info.length; i++) {
            that.data.info[i].timeDifference = that.getTimeDifference(that.data.info[i].lottery_time);
          }
          that.setData({
            info: this.data.info
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      }
    });
  },
  getData(avtiveTag) {
    let json = {};
    console.log(avtiveTag);

    if (avtiveTag == 0) {
      json.team_status = 1; // 正在拼团
    } else if (avtiveTag == 1) {
      json.team_status = 2; // 拼团成功
    } else if (avtiveTag == 2) {
      json.team_status = 3; // 拼团失败
    }
    let urlStr = app.getNetAddresss(app.globalData.store_alone_temp == 1 ? storeAlone : 'plugin.fight-groups.frontend.controllers.fight-groups.get-member-join-teams');
    app._getNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          res.data.data.map(item => {
            let date = new Date(item.has_one_team.start_time * 1000);
            let Y = date.getFullYear() + '-';
            let M =
              (date.getMonth() + 1 < 10 ?
                '0' + (date.getMonth() + 1) :
                date.getMonth() + 1) + '-';
            let D = date.getDate() + ' ';
            let h = date.getHours() + ':';
            let m = date.getMinutes() + ':';
            let s = date.getSeconds() < 10 ? date.getSeconds() + '0' : date.getSeconds();
            item.has_one_team.start_time = Y + M + D + h + m + s;
          });
          this.setData({
            total_page: res.data.last_page,
            isLoadMore: true,
            info: res.data.data,
            page: res.data.current_page,
            is_frequency: res.data.is_frequency,
            member: res.data.member,
            frequency: res.data.frequency
          });
          this.countDown();
          if (!this.data.total_page) {
            this.setData({
              total_page: 0
            });
          }
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      }
    });
  },
  toStore(e) {
    let store_id = e.target.dataset.id || e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/packageC/o2o/HomeSeller/HomeSeller?store_id=' + store_id
    });
  },
  gotoOrder(e) {
    let order_id = e.target.dataset.id || e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/packageA/member/orderdetail/orderdetail?order_id=' + order_id + '&orderType=groups'
    });
  },
  goZhpUrl(e) {
    let item = e.currentTarget.dataset.item;
    let key = e.currentTarget.dataset.key;
    let url, json;
    if (key == 'detail') {
      wx.navigateTo({
        url: '/packageI/newGroup/zhpgroupDetail/zhpgroupDetail?id=' + item.group_id + '&action=2'
      });
    }
    if (key == 'join') {
      url = app.getNetAddresss('plugin.zhp-group-lottery.frontend.order.participate-group');
      json = {
        group_member_id: item.id
      };
      this.joinQuitReq(url, json);
    }
    if (key == 'quit') {
      url = app.getNetAddresss('plugin.zhp-group-lottery.frontend.group-member.cancel-group-member');
      json = {
        group_member_id: item.id
      };
      this.joinQuitReq(url, json);
    }
    if (key == 'order') {
      let order_id = e.currentTarget.dataset.id;
      wx.navigateTo({
        url: '/packageA/member/orderdetail/orderdetail?order_id=' + order_id + '&orderType=zhpGroup'
      });
    }
    console.log(item);
  },
  joinQuitReq(url, json) {
    app._getNetWork({
      url: url,
      data: json,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
          this.getDataZhp(this.data.active);
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      }
    });
  },
  cancelTap(e) {
    let gid = e.currentTarget.dataset.item.id;
    app._getNetWork({
      url: app.getNetAddresss("plugin.zhp-group-lottery.frontend.group-member.quit-msg"),
      data: {
        id: gid
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          let refund_poundage_amount = res.data.refund_poundage_amount;
          if (refund_poundage_amount == 0) {
            this.canceT(gid, '', false);
          } else {
            this.canceT(gid, refund_poundage_amount, true);
          }
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      }
    });

  },
  canceT(gid, refund_poundage_amount, key) {
    let that = this;
    let url = app.getNetAddresss('plugin.zhp-group-lottery.frontend.group-member.quit-group');
    let text = key ? `退团需要扣除退团手续费￥${refund_poundage_amount},退出该团？` : '退出该团';
    wx.showModal({
      title: text,
      content: '',
      success(res) {
        if (res.confirm) {
          app._getNetWork({
            url: url,
            data: {
              id: gid
            },
            success: (resdata) => {
              var res = resdata.data;
              if (res.result == 1) {
                wx.showToast({
                  title: res.msg,
                  icon:'none',
                  duration:1000
                });
                that.getDataZhp(that.data.active);
              } else {
                wx.showToast({
                  icon: 'none',
                  title: res.msg,
                  duration: 1500
                });
              }
            }
          });
        } else if (res.cancel) {
          // console.log('用户点击取消')
        }
      }
    });
  },
  gotoGroup(e) {
    let id = e.target.dataset.item.team_id || e.currentTarget.dataset.item.team_id;
    let store_id = e.target.dataset.item.store_id || e.currentTarget.dataset.item.store_id;
    wx.navigateTo({
      url: '/packageB/member/group/GroupDetail/GroupDetail?id=' + id + '&store_id=' + store_id
    });
  },
  // 获取更多数据，加载更多
  getMoreData() {
    this.setData({
      isLoadMore: false
    });
    let json = {};

    console.log(this.data.page, this.data.total_page);
    let isurl = '';
    if (this.data.type == 'zhpGroup') {
      if (this.data.active == 0) {
        json.is_win = 0; // 正在拼团
      } else if (this.data.active == 1) {
        json.is_win = 1; // 拼团成功
      } else if (this.data.active == 2) {
        json.is_win = 2; // 拼团失败
      }
      isurl = "plugin.zhp-group-lottery.frontend.group-member.get-group-member-list";
    } else {
      if (this.data.active == 0) {
        json.team_status = 1; // 正在拼团
      } else if (this.data.active == 1) {
        json.team_status = 2; // 拼团成功
      } else if (this.data.active == 2) {
        json.team_status = 3; // 拼团失败
      }
      isurl = "plugin.fight-groups.frontend.controllers.fight-groups.get-member-join-teams";
    }
    if (this.data.page >= this.data.total_page) {
      return;
    } else {
      let pages = this.data.page;
      pages += 1;
      this.setData({
        page: pages
      });
      json.page = this.data.page;
      let urlStr = app.getNetAddresss(isurl);
      app._getNetWork({
        url: urlStr,
        data: json,
        success: (resdata) => {
          this.setData({
            isLoadMore: true
          });
          var res = resdata.data;
          if (res.result == 1) {

            var nextPageData = res.data.data;
            if (this.data.type == 'zhpGroup') {
              for (let i = 0; i < this.data.info.length; i++) {
                this.data.info[i].timeDifference = this.getTimeDifference(this.data.info[i].lottery_time);
              }
              this.setData({
                info: this.data.info
              });
              let info = [...this.data.info, ...nextPageData];
              this.setData({
                info,
                page: res.data.current_page
              });
              return;
            }
            nextPageData.map(item => {
              let date = new Date(item.has_one_team.start_time * 1000);
              let Y = date.getFullYear() + '-';
              let M =
                (date.getMonth() + 1 < 10 ?
                  '0' + (date.getMonth() + 1) :
                  date.getMonth() + 1) + '-';
              let D = date.getDate() + ' ';
              let h = date.getHours() + ':';
              let m = date.getMinutes() + ':';
              let s = date.getSeconds() < 10 ? date.getSeconds() + '0' : date.getSeconds();

              item.has_one_team.start_time = Y + M + D + h + m + s;
            });

            let info = [...this.data.info, ...nextPageData];
            this.setData({
              info,
              page: res.data.current_page
            });

          } else {
            let p = this.data.page;
            p -= 1;
            this.setData({
              page: p,
              isLoadMore: false
            });
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        }
      });
    }
  },
  changeData(e) {
    if (this.data.type == 'zhpGroup') {
      console.log(e.detail.index);
      this.setData({
        active: e.detail.index,
        info: []
      });
      this.getDataZhp(e.detail.index);
    } else {
      this.setData({
        active: e.detail.index
      });
      this.getData(e.detail.index);
    }

  },
  timeFormat(param) { // 小于10的格式化函数
    return param < 10 ? '0' + param : param;
  },
  countDown() { // 倒计时函数
    // 获取当前时间，同时得到活动结束时间数组
    let newTime = new Date().getTime() / 1000;
    let endTimeList = this.data.info;

    // 对结束时间进行处理渲染到页面
    endTimeList.forEach(o => {

      let endTime = o.has_one_team.end_time;
      // 如果活动未结束，对时间进行处理

      if (endTime - newTime > 0) {
        o.isShowtime = true;
        let time = (endTime - newTime);
        // 获取天、时、分、秒
        let day = parseInt(time / (60 * 60 * 24));
        let hou = parseInt(time % (60 * 60 * 24) / 3600);
        let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
        let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
        o.obj = {
          day: this.timeFormat(day),
          hou: this.timeFormat(hou),
          min: this.timeFormat(min),
          sec: this.timeFormat(sec)
        };
      } else { // 活动已结束，
        o.isShowtime = false;
      }
    });
    // 渲染，然后每隔一秒执行一次倒计时函数
    this.setData({
      info: endTimeList
    });

    this.data.timer = setTimeout(this.countDown, 1000);
  }

});